package service

import (
	"errors"
	"github.com/ulule/deepcopier"
	"go-malphite/app/common/constant"
	"go-malphite/app/common/dto"
	"go-malphite/app/model"
	"go-malphite/app/utils"
	"gorm.io/gorm"
)

// FindUserById 根据用户查找用户
func FindUserById(id int64) (model.User, error) {
	user := model.User{}
	err := utils.DB.Where("user_id = ?", id).First(&user).Error
	if err != nil {
		return user, err
	}
	return user, nil
}

// FindUserByName 根据名称查找用户
func FindUserByName(name string) (model.User, error) {
	user := model.User{}
	err := utils.DB.Where("user_name = ?", name).First(&user).Error
	if err != nil {
		return user, err
	}
	return user, nil
}

// IsExistsUserById 根据id判断用户是否存在
func IsExistsUserById(id int64) bool {
	user := model.User{}
	err := utils.DB.Where("user_id = ?", id).First(&user).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return false
	}
	return true
}

// IsExistsUserByName 根据名称判断用户是否存在
func IsExistsUserByName(name string) bool {
	user := model.User{}
	err := utils.DB.Where("user_name = ?", name).First(&user).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return false
	}
	return true
}

// CreateUser 创建用户
func CreateUser(user model.User) bool {
	tx := utils.DB.Begin()
	defer dto.CommitOrRollback(tx)
	err := tx.Create(&user).Error
	if err != nil {
		return false
	}
	return true
}

// GetDetailUser 获取用户详情
func GetDetailUser(u model.User) (*model.UserOneRes, error) {
	user := new(model.User)
	err := utils.DB.Where("user_id = ?", u.UserId).First(user).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("用户不存在！")
	}
	if err != nil {
		return nil, errors.New("获取用户详情失败！")
	}
	role, _ := FindRoleById(user.RoleId)
	data := &model.UserOneRes{
		UserId:    user.UserId,
		UserName:  user.UserName,
		CreatedAt: user.CreatedAt.Format(constant.DateTimeFormat),
		UpdatedAt: user.UpdatedAt.Format(constant.DateTimeFormat),
		RoleId:    user.RoleId,
		RoleName:  role.RoleName,
	}
	return data, nil
}

// UpdateUser 更新用户
func UpdateUser(u model.User) bool {
	tx := utils.DB.Begin()
	defer dto.CommitOrRollback(tx)
	err := tx.Model(&u).Updates(u).Error
	if err != nil {
		return false
	}
	return true
}

// UpdateUserForName 更新用户名称
func UpdateUserForName(u model.User) bool {
	tx := utils.DB.Begin()
	defer dto.CommitOrRollback(tx)
	err := tx.Model(&u).Update("user_name", u.UserName).Error
	if err != nil {
		return false
	}
	return true
}

// GetListUser 获取用户列表
func GetListUser() ([]model.UserListRes, error) {
	var dataList = make([]model.UserListRes, 0)
	var userList []model.User
	err := utils.DB.Order("created_at desc").Find(&userList).Error
	if err != nil {
		return nil, err
	}
	dict := make(map[int64]string)
	for _, user := range userList {
		var role model.Role
		if value, ok := dict[user.RoleId]; ok {
			role.RoleName = value
		} else {
			role, _ = FindRoleById(user.RoleId)
			dict[user.RoleId] = role.RoleName
		}
		dataList = append(dataList, model.UserListRes{
			UserId:    user.UserId,
			UserName:  user.UserName,
			CreatedAt: user.CreatedAt.Format(constant.DateTimeFormat),
			UpdatedAt: user.UpdatedAt.Format(constant.DateTimeFormat),
			RoleId:    user.RoleId,
			RoleName:  role.RoleName,
		})
	}
	return dataList, nil
}

// GetPageUser 获取用户列表分页
func GetPageUser(page dto.PageReq) (*model.UserPageRes, error) {
	var total int64
	if err := utils.DB.Model(model.User{}).Count(&total).Error; err != nil {
		return nil, errors.New("查询数据异常")
	}
	var records = make([]model.UserOneRes, 0)
	var userList []model.User
	err := utils.DB.Scopes(dto.Paginate(page.Current, page.Size)).Order("created_at desc").Find(&userList).Error
	if err != nil {
		return nil, errors.New("查询数据异常")
	}
	dict := make(map[int64]string)
	for _, user := range userList {
		userOneRes := new(model.UserOneRes)
		err := deepcopier.Copy(user).To(userOneRes)
		if err != nil {
			return nil, errors.New("查询数据异常")
		}
		var role model.Role
		if value, ok := dict[user.RoleId]; ok {
			role.RoleName = value
		} else {
			role, _ := FindRoleById(user.RoleId)
			dict[user.RoleId] = role.RoleName
		}
		userOneRes.CreatedAt = user.CreatedAt.Format(constant.DateTimeFormat)
		userOneRes.UpdatedAt = user.UpdatedAt.Format(constant.DateTimeFormat)
		userOneRes.RoleName = role.RoleName
		records = append(records, *userOneRes)
	}
	userPageRes := &model.UserPageRes{
		PageRes: dto.PageRes{
			Current: page.Current,
			Size:    page.Size,
			Total:   total,
		},
		Records: records,
	}
	return userPageRes, nil
}

// RemoveUser 删除用户
func RemoveUser(u model.User) bool {
	tx := utils.DB.Begin()
	defer dto.CommitOrRollback(tx)
	err := tx.Where("user_id = ?", u.UserId).Delete(&u).Error
	if err != nil {
		return false
	}
	return true
}
